package wht.jly.forum.service.impl;

import com.querydsl.core.BooleanBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import wht.jly.forum.domain.QRole;
import wht.jly.forum.domain.Role;
import wht.jly.forum.repository.RoleRepository;
import wht.jly.forum.service.RoleService;
import wht.jly.forum.utils.PropertyUtils;

import javax.transaction.Transactional;
import java.util.Optional;

/**
 * @author lanyangji
 * @date 2019/2/11 17:31
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public Page<Role> findByCondition(Integer page, Integer size, Role role) {
        // 拼接查询条件
        QRole dbRole = QRole.role;
        BooleanBuilder builder = new BooleanBuilder();
        if (!StringUtils.isEmpty(role.getRoleName())) {
            builder.and(dbRole.roleName.like("%" + role.getRoleName() + "%"));
        }
        if (role.getId() != null) {
            builder.or(dbRole.id.intValue().eq(role.getId()));
        }

        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, sort);

        return roleRepository.findAll(builder, pageable);
    }

    @Override
    public Role findById(Integer id) {
        if (id != null) {
            Optional<Role> optional = roleRepository.findById(id);
            if (optional.isPresent()) {
                return optional.get();
            }
        }

        return null;
    }

    @Override
    public void deleteById(Integer id) {
        roleRepository.deleteById(id);
    }

    @Override
    public Role updateById(Role role) {
        if (role.getId() != null) {
            Optional<Role> optional = roleRepository.findById(role.getId());
            if (optional.isPresent()) {
                Role dbRole = optional.get();
                BeanUtils.copyProperties(role, dbRole, PropertyUtils.getNullPropertyNames(role));
                return roleRepository.save(dbRole);
            }
        }

        return null;
    }
}
